package net.cctms.zhishu.webAppFramework.utils;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;

import net.cctms.zhishu.R;
import net.cctms.zhishu.webAppFramework.ui.view.ShareDialog;
import net.cctms.zhishu.webAppFramework.ui.view.SharePopupWindow;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * 分享弹出工具类
 *
 * @author yf on 2017/8/8
 */

public class ShareDialogUtil {
    private static final String TAG = ShareDialogUtil.class.getSimpleName();
    public static String articleId;
    public static boolean isActivityShare = false;
    public static final int THUMB_SIZE = 100;

    /*
    public static void recommendToFriends(final Activity activity) {

        String recommendTitle = activity.getResources().getString(R.string.recommend_to_friends_title);
        String recommendContent = activity.getResources().getString( R.string.recommend_to_friends_content);
        String recommendUrl = Config.RECOMMEND_TO_FRIENDS_URL;
        String recommendPicUrl = activity.getResources().getString(R.string.recommend_to_friends_pic_url);
        Bitmap recommendPicBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_share);

        final ShareEntity shareEntity = new ShareEntity();
        shareEntity.shareBitmap = recommendPicBitmap;
        shareEntity.shareTitle = recommendTitle;
        shareEntity.shareUrl = recommendUrl;
        shareEntity.sharePicUrl = recommendPicUrl;
        shareEntity.shareContent = recommendContent;
        isActivityShare = false;

        showDialog(activity, new ShareDialog.OnShareItemClickListener() {
            @Override
            public void onShareItemClick(int position) {
                if (NetUtil.isNetworkAvailable(activity)) {
                    shareItemClickHelper(activity, position, shareEntity);
                } else {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.net_not_available));
                }
            }
        });
    }
    */

    /**
     * 活动页面分享
     */
    /*
    public static void shareActivityToFriends(final Activity activity, String shareTitle, String shareSummary, String shareUrl) {
        String recommendPicUrl = activity.getResources().getString(R.string.recommend_to_friends_pic_url);
        Bitmap recommendPicBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_share);

        final ShareEntity shareEntity = new ShareEntity();
        shareEntity.shareBitmap = recommendPicBitmap;
        shareEntity.shareTitle = shareTitle;
        shareEntity.shareUrl = shareUrl;
        shareEntity.sharePicUrl = recommendPicUrl;
        shareEntity.shareContent = shareSummary;
        shareEntity.isActivityShare = true;
        isActivityShare = true;

        ShareDialog dialog = new ShareDialog(activity, true);
        dialog.setOnItemClickListener(new ShareDialog.OnShareItemClickListener() {
            @Override
            public void onShareItemClick(int position) {
                if (NetUtil.isNetworkAvailable(activity)) {
                    shareItemClickHelper(activity, position, shareEntity);
                } else {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.net_not_available));
                }
            }
        });
        dialog.show();

    }
    */

    /**
     * 分享对话框弹出方法
     *
     * @param activity
     * @param onShareItemClickListener
     */
    public static void showDialog(Activity activity, ShareDialog.OnShareItemClickListener onShareItemClickListener) {

        ShareDialog dialog = new ShareDialog(activity);
        dialog.setOnItemClickListener(onShareItemClickListener);
        dialog.show();

        isActivityShare = false;
    }

   /* *//**
     * 获取分享发起页的根布局
     *
     * @param activity
     * @return
     *//*
    private static View getRootView(Activity activity) {
        return ((ViewGroup) activity.findViewById(android.R.id.content)).getChildAt(0);
    }*/

    /**
     * 分享对话框点击事件处理方法
     *
     * @param position
     * @param shareEntity
     */
    public static void shareItemClickHelper(final Activity activity, final int position, final ShareEntity shareEntity) {
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(new Runnable() {
            @Override
            public void run() {
                handleShareItemClick(activity, position, shareEntity);
            }
        });
    }

    /**
     * 分享对话框点击事件处理方法
     *
     * @param position
     * @param shareEntity
     * @param activity
     */
    private static void handleShareItemClick(final Activity activity, final int position, final ShareEntity shareEntity) {
        if (!NetUtil.isNetworkAvailable(activity)) {
            ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.net_not_available));
            return;
        }

        if (TextUtils.isEmpty(shareEntity.shareTitle)) {
            ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.share_fail));
            return;
        }

        if (TextUtils.isEmpty(shareEntity.shareContent)) {
            shareEntity.shareContent = shareEntity.shareTitle;
        }

        if (!TextUtils.isEmpty(shareEntity.articleId)) {
            //UEDAgent.trackCustomKVEvent(activity, "articleDetail_shareButton", null, null);
        } else {
            //推荐给朋友
        }

        if (position != SharePopupWindow.WEIBO) {
            //判断分享缩略图链接是否为空
            if (!TextUtils.isEmpty(shareEntity.sharePicUrl)) {
                if (position != SharePopupWindow.QZONE && position != SharePopupWindow.QQ) {
                    Glide.with(activity).loadFromMediaStore(Uri.parse(shareEntity.sharePicUrl)).downloadOnly(new SimpleTarget<File>() {
                        @Override
                        public void onResourceReady(File file, GlideAnimation<? super File> glideAnimation) {
                            try{
                                if (file != null) {
                                    Bitmap originalBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
                                    try {
                                        if (originalBitmap.getHeight() > THUMB_SIZE || originalBitmap.getWidth() > THUMB_SIZE) {
                                            shareEntity.shareBitmap = Bitmap.createScaledBitmap(originalBitmap, THUMB_SIZE, THUMB_SIZE, true);
                                            if (!originalBitmap.isRecycled()) {
                                                originalBitmap.recycle();
                                                System.gc();
                                            }
                                        } else {
                                            shareEntity.shareBitmap = originalBitmap;
                                        }
                                    } catch (Exception e) {
                                        shareEntity.shareBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_share);
                                    }
                                    dispatchShareEvent(activity, shareEntity, position);
                                }else {
                                    shareEntity.shareBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_share);
                                    dispatchShareEvent(activity, shareEntity, position);
                                }
                            }catch (Exception e){
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onLoadFailed(Exception e, Drawable errorDrawable) {
                            shareEntity.shareBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_share);
                            dispatchShareEvent(activity, shareEntity, position);
                        }
                    });
                } else {
                    dispatchShareEvent(activity, shareEntity, position);
                }
            } else {
                shareEntity.shareBitmap = BitmapFactory.decodeResource(activity.getResources(), R.mipmap.ic_launcher_share);
                shareEntity.sharePicUrl = activity.getString(R.string.recommend_to_friends_pic_url);
                dispatchShareEvent(activity, shareEntity, position);
            }
        } else {
            dispatchShareEvent(activity, shareEntity, position);
        }
    }


    public static void dispatchShareEvent(final Activity activity, final ShareEntity shareEntity, int position) {
        switch (position) {
            /*
            case SharePopupWindow.QQ:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_QQ;
                reportData(activity, shareEntity, true);
                shareToQQ(activity, shareEntity);
                break;
            case SharePopupWindow.QZONE:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_QZONE;
                reportData(activity, shareEntity, true);
                shareToQZone(activity, shareEntity);
                break;
            case SharePopupWindow.WEIXIN_FRIENDS:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_WEIXIN;
                shareToWeiXinFriends(activity, shareEntity);
                break;
            case SharePopupWindow.WEXIN:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_WEIXIN;
                shareToWeiXin(activity, shareEntity);
                break;
            case SharePopupWindow.WEIBO:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_WEIBO;
                reportData(activity, shareEntity, true);
                shareToWeiBo(activity, shareEntity);
                break;
            case SharePopupWindow.SMS:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_SMS;
                reportData(activity, shareEntity, true);
                shareToSms(activity, shareEntity);
                break;
            case SharePopupWindow.MINI:
                shareEntity.shareChannel = com.cn21.android.news.utils.Constants.KEY_SHARE_CHANNEL_WEIXIN;
                shareToWeiXinMini(activity, shareEntity);
                break;
            default:
                break;
                */
        }
    }

    /*
    //分享到微信小程序
    private static void shareToWeiXinMini(final Activity activity, final ShareEntity shareEntity) {
        articleId = shareEntity.articleId;
        WeiXinShareBean weiXinMini = new WeiXinShareBean();
        weiXinMini.setDescription(shareEntity.shareContent);
        weiXinMini.setUrl(shareEntity.shareUrl);
        weiXinMini.setBitmap(shareEntity.shareBitmap);
        weiXinMini.setTitle(shareEntity.shareTitle);
        weiXinMini.setLocalResImg(R.mipmap.ic_launcher_share);
        weiXinMini.setLocalResImgSize(100);
        weiXinMini.setUserName(com.cn21.android.news.utils.Constants.WEIXIN_MINI_ID);
        weiXinMini.setWebpageUrl("http://www.21cn.com");
        weiXinMini.setPath("/pages/circleDetail/circleDetail?id=77cac0c99d98b03d");
        ShareUtil.shareToWXMini(activity, weiXinMini, new IResponseListener() {
            @Override
            public void onResult(int i, String s) {
                if (i == com.cn21.share.factory.Constants.APP_IS_INSTALLED) {
                    if (!TextUtils.isEmpty(shareEntity.articleId)) {
                        reportData(activity, shareEntity, true);
                    }
                } else if (i == Constants.APP_NOT_INSTALLED) {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.weixin_not_install));
                }
            }
        });
    }
    */

    /*
    public static void handleWeiXinResponse(Context context, BaseResp resp) {
        ReportEntity reportEntity = new ReportEntity();
        reportEntity.objId = articleId;
        reportEntity.isActivityShare = isActivityShare;
        ShareUtil.handleWeiXinResponse(context, resp, reportEntity);
    }
    */

    /*
    private static void shareToQQ(final Activity activity, final ShareEntity shareEntity) {
        QQShareBean qqShareBean = new QQShareBean();
        qqShareBean.setDescription(shareEntity.shareContent);
        qqShareBean.setTitle(shareEntity.shareTitle);
        qqShareBean.setUrl(shareEntity.shareUrl);
        qqShareBean.setImageUrl(shareEntity.sharePicUrl);
        ShareUtil.shareToQQ(activity, qqShareBean, new ShareUtil.ShareListener() {
            @Override
            public void onSuccess() {
                if (!TextUtils.isEmpty(shareEntity.articleId)) {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.share_success));
                    UEDAgent.trackCustomKVEvent(activity, "articleDetail_shareTotal", null, null);
                } else if (TextUtils.isEmpty(shareEntity.articleId) && !shareEntity.isActivityShare) {
                    //判断是否为分享给朋友
                    UEDAgent.trackCustomKVEvent(activity, "me_shareToFriends", null, null);
                }

                if (shareEntity.isActivityShare) {
                    ShareUtil.sendShareSuccess(activity);
                }

                ShareUtil.postShareEvent(shareEntity.articleId);
            }

            @Override
            public void onError() {
            }

            @Override
            public void onCancel() {
            }
        });
    }
    */

    /*
    private static void shareToQZone(final Activity activity, final ShareEntity shareEntity) {
        QQZoneShareBean qZoneShareBean = new QQZoneShareBean();
        ArrayList<String> sharePicList = new ArrayList<>();
        sharePicList.add(shareEntity.sharePicUrl);
        qZoneShareBean.setDescription(shareEntity.shareContent);
        qZoneShareBean.setImageUrls(sharePicList);
        qZoneShareBean.setTitle(shareEntity.shareTitle);
        qZoneShareBean.setUrl(shareEntity.shareUrl);
        ShareUtil.shareToQZone(activity, qZoneShareBean, new ShareUtil.ShareListener() {
            @Override
            public void onSuccess() {
                if (!TextUtils.isEmpty(shareEntity.articleId)) {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.share_success));
                    UEDAgent.trackCustomKVEvent(activity, "articleDetail_shareTotal", null, null);
                } else if (TextUtils.isEmpty(shareEntity.articleId) && !shareEntity.isActivityShare) {
                    //判断是否为分享给朋友
                    UEDAgent.trackCustomKVEvent(activity, "me_shareToFriends", null, null);
                }

                if (shareEntity.isActivityShare) {
                    ShareUtil.sendShareSuccess(activity);
                }

            }

            @Override
            public void onError() {
            }

            @Override
            public void onCancel() {
            }
        });
    }
    */

    /*
    private static void shareToWeiXin(final Activity activity, final ShareEntity shareEntity) {
        articleId = shareEntity.articleId;

        WeiXinShareBean weiXinShareBean = new WeiXinShareBean();
        weiXinShareBean.setDescription(shareEntity.shareContent);
        weiXinShareBean.setUrl(shareEntity.shareUrl);
        weiXinShareBean.setBitmap(shareEntity.shareBitmap);
        weiXinShareBean.setTitle(shareEntity.shareTitle);
        ShareUtil.shareToWeiXin(activity, weiXinShareBean, new IResponseListener() {
            @Override
            public void onResult(int i, String s) {
                if (i == com.cn21.share.factory.Constants.APP_IS_INSTALLED) {
                    if (!TextUtils.isEmpty(shareEntity.articleId)) {
                        reportData(activity, shareEntity, true);
                    }
                } else if (i == Constants.APP_NOT_INSTALLED) {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.weixin_not_install));
                }
            }
        });
    }
    */

    /*

    public static void shareToWeiXinFriends(final Activity activity, final ShareEntity shareEntity) {
        articleId = shareEntity.articleId;
        if (TextUtils.isEmpty(shareEntity.shareContent)) {
            shareEntity.shareContent = shareEntity.shareTitle;
        }

        WeiXinShareBean weiXinFriendsShareBean = new WeiXinShareBean();
        weiXinFriendsShareBean.setDescription(shareEntity.shareContent);
        weiXinFriendsShareBean.setUrl(shareEntity.shareUrl);
        weiXinFriendsShareBean.setBitmap(shareEntity.shareBitmap);
        weiXinFriendsShareBean.setTitle(shareEntity.shareTitle);

        ShareUtil.shareToWeiXinFriends(activity, weiXinFriendsShareBean, new IResponseListener() {
            @Override
            public void onResult(int i, String s) {
                if (i == Constants.APP_IS_INSTALLED) {
                    if (!TextUtils.isEmpty(shareEntity.articleId)) {
                        reportData(activity, shareEntity, true);
                        CreditsManager.doScore(activity, ActionCode.SHARE_SOCIALCIRCLE,
                                CreditsManager.TYPE_CONTENT, articleId,
                                new CreditsManager.OnCallBack() {
                                    @Override
                                    public void callBackResult(int resultCode, int addCredit, String msg) {
                                        if (resultCode == CreditsManager.RESULT_SUCCESS) {
//                                            ToastUtil.showCreditToast(activity,activity.getString(R.string.share_success),addCredit);
                                        }
                                    }
                                });
                    }
                } else if (i == Constants.APP_NOT_INSTALLED) {
                    ToastUtil.showShortToast(activity, activity.getResources().getString(R.string.weixin_not_install));
                }
            }
        });
    }
    */

    /*
    private static void shareToWeiBo(final Activity activity, final ShareEntity shareEntity) {
        WeiBoShareEntity weiBoShareEntity = new WeiBoShareEntity();
        weiBoShareEntity.articleId = shareEntity.articleId;
        weiBoShareEntity.shareContent = shareEntity.shareContent;
        weiBoShareEntity.sharePicUrl = shareEntity.sharePicUrl;
        weiBoShareEntity.shareTitle = shareEntity.shareTitle + activity.getString(R.string.from_kanjian);
        weiBoShareEntity.shareUrl =  shareEntity.shareUrl;
        weiBoShareEntity.isShareActivity = shareEntity.isActivityShare;
        SinaWeiBoShareActivity.openActivity(activity, weiBoShareEntity);
    }
    */

    /*
    private static void shareToSms(Activity activity, ShareEntity shareEntity) {
        ShareBean shareBean = new ShareBean();
        shareBean.setTitle(shareEntity.shareTitle);
        shareBean.setDescription(shareEntity.shareContent);
        shareBean.setUrl(shareEntity.shareUrl);
        if (TextUtils.isEmpty(shareEntity.articleId)) {
            ShareUtil.shareToSmsApp(activity, shareBean);
        } else {
            ShareUtil.shareToSms(activity, shareBean);
        }
    }
    */

    public static class ShareEntity implements Serializable {
        public String articleId;
        public String shareTitle;
        public String shareContent;
        public String shareUrl;
        public String sharePicUrl;
        public Bitmap shareBitmap;
        public String shareChannel;
        public String objectId;
        public int type;
//        public ShareReportListener shareReportListener;
        public boolean isActivityShare = false;
    }

    /**
     * 分享数据上报
     *
     * @param activity
     * @param shareEntity
     * @param isSuccess
     */
    /*
    private static void reportData(Activity activity, final ShareEntity shareEntity, boolean isSuccess) {
        if (!TextUtils.isEmpty(shareEntity.articleId)) {
            //UserDataReportUtil.getInstance().articleShareReport(activity, shareEntity.articleId, shareEntity.shareChannel,isSuccess);
            UserDataReportUtil.getInstance().articleShareReport(activity, shareEntity.articleId, shareEntity.shareChannel, isSuccess, new ShareReportListener() {
                @Override
                public void onSuccess() {
                    BusProvider.share(shareEntity.articleId);
                }

                @Override
                public void onError() {

                }
            });
        }
    }


    public interface ShareReportListener{
        void onSuccess();
        void onError();
    }
     */

}
